package com.softjourn.punchcard.merchant.activity;

import java.util.concurrent.ExecutionException;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockActivity;

import com.softjourn.punchcard.merchant.R;
import com.softjourn.punchcard.merchant.lib.ApiFunctions;
import com.softjourn.punchcard.merchant.lib.NetworkUtil;
import com.softjourn.punchcard.merchant.lib.PropertiesStorage;
import com.softjourn.punchcard.merchant.model.ApiResponse;
import com.softjourn.punchcard.merchant.model.Client;
import com.softjourn.punchcard.merchant.model.ClientResponse;
import com.softjourn.punchcard.merchant.model.ProductsResponse;
import com.softjourn.punchcard.merchant.model.PunchCard;

public class ClientActivity extends SherlockActivity {

	private PropertiesStorage propertiesStorage;

	Button btnCancel;
	Button btnAddBonus;

	TextView clientName;
	TextView clientEmail;
	TextView clientMarkCount;
	
	Dialog dialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		propertiesStorage = new PropertiesStorage(this);

		setContentView(R.layout.activity_client);

		btnCancel = (Button) findViewById(R.id.btn_client_cancel);
		btnAddBonus = (Button) findViewById(R.id.btn_add_bonus);

		clientName = (TextView) findViewById(R.id.client_name);
		clientEmail = (TextView) findViewById(R.id.client_email);
		clientMarkCount = (TextView) findViewById(R.id.client_mark_count);

		if (NetworkUtil.isConnectivityActive(getApplicationContext())) {

			try {

				String salePointUid = propertiesStorage.getActiveSalePoint();
				final String clientUid = propertiesStorage.getActiveClient();

				ClientResponse clientResponse = new ClientInfoAsyncTask()
						.execute(clientUid).get();

				if (clientResponse.getStatus().equals("OK")) {

					Client client = clientResponse.getClient();
					PunchCard punchCard = clientResponse.getPunchCard();
					if (client != null || punchCard != null) {
						clientName.setText(client.getName());
						clientEmail.setText(client.getEmail());
						clientMarkCount.setText("" + punchCard.getBonuses());
					} else {
						// server error mess
					}
				} else {
					// server error mess
				}
				
				final ProductsResponse productsResponse = new ProductsAsyncTask()
						.execute(salePointUid).get();

				if (productsResponse != null) {

					btnAddBonus.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							String productId = Integer
									.toString(productsResponse.getProducts()
											.get(0).getId());

							ApiResponse apiResponse = null;

							try {
								apiResponse = new AddBonusesAsyncTask()
										.execute(clientUid, productId).get();
								
								if (apiResponse.getStatus().equals("OK")) {
									showMessageDialog(getString(R.string.add_success));
								} else {
									showMessageDialog(getString(R.string.add_error)
											+ apiResponse.getStatus());
								}
								
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (ExecutionException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					});
				} else {
					// server error mess
				}
			

				// cancel button should take us to activity_main layout
				btnCancel.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
		
						overridePendingTransition(0, 0);
						finish();
					}
				});

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} else {

		}
	}
	
	private void showMessageDialog(String message) {
		
		dialog = new Dialog(this,R.style.Theme_Punchcard_PopUpDialog);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_message);
		
		ColorDrawable dialogColor = new ColorDrawable(Color.WHITE);
		dialogColor.setAlpha(220);
		dialog.getWindow().setBackgroundDrawable(dialogColor);
		
		TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialogMessage);
		Button btnReturn = (Button) dialog.findViewById(R.id.btnReturn);
		
		dialogMessage.setText(message);
		
		btnReturn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		
		dialog.setCanceledOnTouchOutside(true);
		
		dialog.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				finish();
			}
		});
		
		dialog.show();
	}

	private class AddBonusesAsyncTask extends
			AsyncTask<String, Void, ApiResponse> {

		@Override
		protected ApiResponse doInBackground(String... params) {

			ApiFunctions merchantFunction = new ApiFunctions(
					ClientActivity.this);
			try {
				ApiResponse response = merchantFunction.addBonuses(params[0],
						params[1]);
				Log.i("OK", response.toString());
				return response;

			} catch (Exception e) {
				Log.e("EXCEPTION", e.getMessage());
			}

			return null;
		}
	}

	private class ProductsAsyncTask extends
			AsyncTask<String, Void, ProductsResponse> {

		@Override
		protected ProductsResponse doInBackground(String... params) {

			ApiFunctions merchantFunction = new ApiFunctions(
					ClientActivity.this);
			try {
				ProductsResponse response = merchantFunction
						.getProducts(params[0]);
				Log.i("OK", response.toString());
				return response;

			} catch (Exception e) {
				Log.e("EXCEPTION", e.getMessage());
			}

			return null;
		}
	}

	private class ClientInfoAsyncTask extends
			AsyncTask<String, Void, ClientResponse> {

		@Override
		protected ClientResponse doInBackground(String... params) {

			ApiFunctions merchantFunction = new ApiFunctions(
					ClientActivity.this);
			try {
				ClientResponse response = merchantFunction
						.clientInfo(params[0]);
				Log.i("OK", response.toString());
				return response;

			} catch (Exception e) {
				Log.e("EXCEPTION", e.getMessage());
			}

			return null;
		}
	}

}
